package com.zy.cat.common.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
//import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
 
/**
 * 前后端数据传输加密工具类
 * @author monkey
 *
 */
public class AesEncryptUtils {
    //可配置到Constant中，并读取配置文件注入,16位,自己定义
    private static final String KEY = "zy*#!@#$%^&*2019";
 
    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
 
    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    private static String encrypt(String content, String encryptKey){
        KeyGenerator kgen;
        byte[] binaryData = null;
		try {
			kgen = KeyGenerator.getInstance("AES");
	        kgen.init(128);
	        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
	        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
	        binaryData = cipher.doFinal(content.getBytes("utf-8"));
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidKeyException e) {
			return "";
		}
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64URLSafeString(binaryData);
 
    }
 
    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    private static String decrypt(String encryptStr, String decryptKey){
        KeyGenerator kgen;
        byte[] decryptBytes;
		try {
			kgen = KeyGenerator.getInstance("AES");
		       kgen.init(128);
		        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
		        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
		        // 采用base64算法进行转码,避免出现中文乱码
		        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
		        decryptBytes = cipher.doFinal(encryptBytes);
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
			return "";
		}
        return new String(decryptBytes);
    }
    
    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @param decryptIv 解密的iv值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey,String iv){
        KeyGenerator kgen;
        byte[] decryptBytes;
		try {
			kgen = KeyGenerator.getInstance("AES");
		       kgen.init(128);
		        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		        Key sKeySpec = new SecretKeySpec(Base64.decodeBase64(decryptKey), "AES");
		        cipher.init(Cipher.DECRYPT_MODE, sKeySpec,generateIV(Base64.decodeBase64(iv)));
		        // 采用base64算法进行转码,避免出现中文乱码
		        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
		        decryptBytes = cipher.doFinal(encryptBytes);
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
			return "";
		} catch (Exception e) {
			return "";
		}
        return new String(decryptBytes);
    }
    
    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }
    
    /**
     * @加盐加密
     * @author Link
     * @date 2019-06-26 17:32
     * @param content
     * @param encryptKey
     * @return
     * @throws Exception
     */
    public static String encryptBySalt(String content) {
    	content+=UUID.randomUUID().toString().substring(26);
        return encrypt(content);
    }
    
    /**
     * @加盐加密
     * @author Link
     * @date 2019-06-26 17:32
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBySalt(String content,String key) {
        return encrypt(content,key);
    }
    
    /**
     * @解密加密
     * @author Link
     * @date 2019-06-26 17:38
     * @param encryptStr
     * @param decryptKey
     * @return
     * @throws Exception
     */
    public static String decryptBySalt(String encryptStr) {
    	if(StringUtils.isBlank(encryptStr)) {
    		return null;
    	}
         String des=decrypt(encryptStr);
         if(StringUtils.isNotBlank(des)) {
        	 des=des.substring(0,des.length()-10);
         }
        return des;
    }
    
    /**
     * @解密加密
     * @author Link
     * @date 2019-06-26 17:38
     * @param encryptStr
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptBySalt(String encryptStr,String key) {
    	if(StringUtils.isBlank(encryptStr)) {
    		return null;
    	}
         String des=decrypt(encryptStr,key);
        return des;
    }
 
    public static String encrypt(String content) {
        try {
			return encrypt(content, KEY);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
    public static String decrypt(String encryptStr) {
        try {
			return decrypt(encryptStr, KEY);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
 
 
    public static void main(String[] args){
    	
//    	for (int i = 0; i < 10; i++) {
//    		String en=encryptBySalt("123456789");
//    		System.out.println("加密后："+en);
//    		System.out.println("解密后："+decryptBySalt(en));
//		}
    	System.out.println(decrypt("jW1pq7dWvug78phcDX-Ptg"));
    	
// String uuname="bwDedBHY4CCDSYtRxxmijpYQ2ZQrI8nDIBCDvnlok-E8APpXNhwqb_M5dBe7JQTbg2LV1LxprOhm72kxG6vF5w";
// String uuid="f04xrGyesM0yI5MAjxbOYQ";
// String uutid="Diogtuvm4TZACw2J4sPNAA";
// 
////        Map map=new HashMap<String,String>();
////        map.put("key","value");
////        map.put("中文","汉字");
////        String content = JSONObject.toJSONString(map);
////        System.out.println("加密前：" + content);
//// 
//// 
//        String decrypt = decrypt(uutid, KEY);
//        System.out.println(DateUtil.compareDate("2019-06-06", LocalDate.now().toString())+"解密后：" + decrypt);
    }
}
 